import React, { useEffect, useState, useImperativeHandle } from 'react';
import {
  Tag,
  Empty,
  Select,
  Form,
  Icon,
  Divider,
  Radio,
  Row,
  Col,
  Input,
  Button,
  Spin,
  message,
  // Modal,
} from 'antd';
import { connect } from 'dva';
import classNames from 'classnames';
import cloneDeep from 'lodash/cloneDeep';
import groupBy from 'lodash/groupBy';
import request from '@/utils/request';
import ConditionSet from './ConditionSet';
// import ParamsChangeComp from './ParamsChangeComp';
import ConditionView from './ConditionView';
import ComboGrid from '@/components/ComboGrid';
import styles from '../index.less';

const { Option } = Select;

function Content({ form, operType, ruleId, planInfo, cRef }) {
  const { getFieldDecorator } = form;
  const [data, setData] = useState({});
  const [result, setResult] = useState([]);
  const [loading, setLoading] = useState(false);
  // 保存记录type：rule 的模式 精简模式：simplify  操作模式：operate
  const [rulePattern, setRulePattern] = useState('simplify');

  // 设置条件、规则结果模态弹窗
  const [conditVisiable, setConditVisiable] = useState(false);
  // 设置条件、规则结果条件入参  set 表示为条件、rule 表示为结果设置
  const [conditStatus, setConditStatus] = useState('');
  // 条件设置条件预览模态框
  const [conditViewVisiable, setConditViewVisiable] = useState(false);

  async function query() {
    let result;
    await Promise.all([
      request('pmc/pms/RuleCfgController/showRuleCond', {
        data: {
          ruleId,
        },
      }),
      request('pmc/pms/StaticDataController/batchQueryStaticAttr.do', {
        data: ['RULE_COND_COMBOBOX'],
      }),
    ]).then(res => {
      result = res;
    });
    return result;
  }

  useEffect(() => {
    setRulePattern('simplify');
    form.resetFields('transAssId');
    if (operType === 'add' && ruleId === '') {
      setData({});
      setLoading(true);
      request('pmc/pms/StaticDataController/batchQueryStaticAttr.do', {
        data: ['RULE_COND_COMBOBOX'],
      })
        .then(res => {
          if (res.success) {
            setResult(res.data.RULE_COND_COMBOBOX);
          } else {
            message.error(res.errMessage);
          }
        })
        .always(() => {
          setLoading(false);
          form.setFieldsValue({
            planName: planInfo.planName,
            planId: planInfo.planId,
          });
        });
    } else if (operType === 'detail' && ruleId !== 'none_status' && ruleId !== '') {
      setLoading(true);
      query()
        .then(res => {
          if (res[0].success && res[1].success) {
            setData(res[0].data);
            setResult(res[1].data.RULE_COND_COMBOBOX);
            if (res[0].data.ruleCO) {
              // 参数转化comborgrid的处理
              let obj = {};
              if (res[0].data.ruleCO.transAssId) {
                obj = {
                  transAssId: [
                    {
                      assName: res[0].data.ruleCO.transAssName,
                      assId: res[0].data.ruleCO.transAssId,
                    },
                  ],
                };
              }

              form.setFieldsValue({
                ruleName: res[0].data.ruleCO.ruleName,
                ruleCode: res[0].data.ruleCO.ruleCode,
                assId: [{ assName: res[0].data.ruleCO.assName, assId: res[0].data.ruleCO.assId }],
                planName: res[0].data.ruleCO.planName,
                planId: res[0].data.ruleCO.planId,
                ruleDesc: res[0].data.ruleCO.ruleDesc,
                ...obj,
              });
            }
          } else {
            message.error('接口请求有误！请检查');
          }
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [ruleId]);

  // 精简操作与操作模式的切换
  const rulePatternChange = e => {
    setRulePattern(e.target.value);
  };

  const callBack = value => {
    const data2 = cloneDeep(data);

    // 有attrId
    const hasidValue = value.filter(item => item.attr.attrId !== '');
    // 无attrId
    const noIdValue = value.filter(item => item.attr.attrId === '');

    const obj = groupBy(hasidValue, function(item) {
      return item.attr.attrId;
    });
    const arr = [];
    /* eslint-disable */
    for (let key in obj) {
      arr.push(obj[key]);
    }

    noIdValue.map(item => {
      arr.push([item]);
    });

    /* eslint-enable */
    if (conditStatus === 'set') {
      data2.ruleCondList = arr;
      setData(data2);
    } else {
      data2.ruleConstList = arr;
      setData(data2);
    }
  };

  // const onSubmit = () => {
  //   form.validateFields((err, fieldsValue) => {
  //     if (err) return;
  //     // console.log(fieldsValue);

  //   });
  // };

  useImperativeHandle(cRef, () => ({
    handleAdd: () => {
      return new Promise(function(resolve) {
        form.validateFields((err, fieldsValue) => {
          if (err) return;
          let paramsObj = {};
          if (operType === 'add') {
            paramsObj = {
              ruleCO: {
                ...fieldsValue,
                assId:
                  fieldsValue.assId && fieldsValue.assId.length ? fieldsValue.assId[0].assId : '',
                transAssId:
                  fieldsValue.transAssId && fieldsValue.transAssId.length
                    ? fieldsValue.transAssId[0].assId
                    : '',
                actionType: 'add',
                pid: fieldsValue.planId ? fieldsValue.planId : '',
              },
              ruleCondList: data.ruleCondList,
              ruleConstList: data.ruleConstList,
            };
          } else {
            paramsObj = {
              ruleCO: {
                ...fieldsValue,
                assId:
                  fieldsValue.assId && fieldsValue.assId.length ? fieldsValue.assId[0].assId : '',
                transAssId:
                  fieldsValue.transAssId && fieldsValue.transAssId.length
                    ? fieldsValue.transAssId[0].assId
                    : '',
                actionType: 'edit',
                ruleId,
                pid: fieldsValue.planId ? fieldsValue.planId : '',
              },
              ruleCondList: data.ruleCondList,
              ruleConstList: data.ruleConstList,
            };
          }

          setLoading(true);
          request('pmc/pms/RuleCfgController/saveRuleAndCond', {
            data: paramsObj,
          })
            .then(res => {
              if (res.success) {
                message.success('操作成功！');
                resolve(true);
              } else {
                message.error(res.errMessage);
              }
            })
            .always(() => {
              setLoading(false);
            });
        });
      });
    },
  }));

  const handleClose = tag  => {
    const newRuleCondList = [];
    data.ruleCondList.forEach((data1,index) => {
      const newData = [];
      data1.map(item => {
        if(tag.attrValue !== item.attrValue){
           newData.push(item);
        }
      });
      if(newData.length > 0){
        newRuleCondList.push(newData);
      }
    });
    const data2 = cloneDeep(data);
    data2.ruleCondList = newRuleCondList;
    setData(data2);
    // alert(JSON.stringify(newRuleCondList));
  };

  return (
    <>
      <Spin spinning={loading}>
        <div className="ant-detail-title">
          <span className="padding-right">规则设置</span>

          <Radio.Group
            className="pull-right"
            value={rulePattern}
            size="small"
            buttonStyle="solid"
            onChange={rulePatternChange}
          >
            <Radio.Button value="simplify">精简模式</Radio.Button>
            <Radio.Button value="operate">操作模式</Radio.Button>
          </Radio.Group>
        </div>

        <Form layout="vertical">
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="规则名称">
                {getFieldDecorator('ruleName', {
                  rules: [
                    {
                      required: true,
                      message: '规则名称不能为空',
                    },
                  ],
                })(<Input placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="规则编码">
                {getFieldDecorator('ruleCode')(<Input allowClear placeholder="请输入" disabled />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="组件设置">
                {getFieldDecorator('assId', {
                  rules: [
                    {
                      required: true,
                      message: '组件设置不能为空',
                    },
                  ],
                })(
                  <ComboGrid
                    url="pmc/pms/RuleCfgController/findAssemblyPageQry"
                    popupStyle={{ width: 560 }}
                    placeholder="请选择"
                    destroyPopupOnHide
                    searchPlaceholder="请输入组件名称进行搜索"
                    label="assName"
                    rowKey="assId"
                    pick="radio"
                    params={{ assType: '1' }}
                    columns={[
                      {
                        title: '组件名称',
                        dataIndex: 'assName',
                      },
                      {
                        title: '组件编码',
                        dataIndex: 'assCode',
                        ellipsis: true,
                      },
                    ]}
                  />
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="关联方案">
                {getFieldDecorator('planName')(<Input allowClear placeholder="请输入" disabled />)}
              </Form.Item>
            </Col>
            <Col span={6} hidden>
              <Form.Item label="关联方案ID">
                {getFieldDecorator('planId')(<Input allowClear placeholder="请输入" disabled />)}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="入参转换组件">
                {getFieldDecorator('transAssId')(
                  <ComboGrid
                    url="pmc/pms/RuleCfgController/findAssemblyPageQry"
                    popupStyle={{ width: 560 }}
                    placeholder="请选择"
                    searchPlaceholder="请输入组件名称进行搜索"
                    destroyPopupOnHide
                    label="assName"
                    rowKey="assId"
                    pick="radio"
                    params={{ assType: '0' }}
                    columns={[
                      {
                        title: '组件名称',
                        dataIndex: 'assName',
                      },
                      {
                        title: '组件编码',
                        dataIndex: 'assCode',
                        ellipsis: true,
                      },
                    ]}
                  />
                )}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="规则描述">
                {getFieldDecorator('ruleDesc')(
                  <Input.TextArea rows={4} placeholder="请输入描述" />
                )}
              </Form.Item>
            </Col>
          </Row>
        </Form>

        <Divider className="small" />
        <div className="ant-detail-title">
          <span className="padding-right">条件设置</span>
          <span className="pull-right">
            <Button.Group>
              <Button
                ghost
                type="primary"
                onClick={() => {
                  setConditVisiable(true);
                  setConditStatus('set');
                }}
              >
                <Icon type="plus" />
                添加条件
              </Button>

              <Button
                type="primary"
                ghost
                onClick={() => {
                  setConditViewVisiable(true);
                }}
              >
                <Icon type="eye" />
                条件预览
              </Button>
            </Button.Group>
          </span>
        </div>
        <div className={styles.rule_form}>
          {data.ruleCondList && data.ruleCondList.length > 0 ? (
            data.ruleCondList.map((tag, index) => (
              <>
                <div hidden={rulePattern === 'simplify'}>
                  <Select
                    style={{ width: 100 }}
                    className="margin-bottom"
                    placeholder="请选择"
                    allowClear
                    value={tag[0].leftBrackets}
                    onChange={value => {
                      const data1 = cloneDeep(data);
                      data1.ruleCondList[index].map(item => {
                        item.leftBrackets = value;
                      });
                      setData(data1);
                    }}
                  >
                    <Option value="(">(</Option>
                  </Select>
                </div>

                <div style={{ paddingLeft: rulePattern === 'simplify' ? 0 : '108px' }}>
                  <div className={styles.rule_title}>
                    {tag[0].attr.attrId ? tag[0].attr.attrName : tag[0].attr.attrCode}
                  </div>
                  <div style={{display:'inline-block'}}>
                    <Select
                      style={{ width: 200 }}
                      placeholder="请选择"
                      allowClear
                      value={tag[0].optType}
                      onChange={value => {
                        const data1 = cloneDeep(data);
                        data1.ruleCondList[index].map(item => {
                          item.optType = value;
                        });
                        setData(data1);
                      }}
                    >
                      {result.map(item => {
                        return (
                          <Option key={item.attrValue} value={item.attrValue}>
                            {item.attrValueName}
                          </Option>
                        );
                      })}
                    </Select>
                    <span className={classNames(styles.rule_tag)}>
                      {tag.map(i => (
                        <Tag key={i.attrValue} closable onClose={() => handleClose(i)}>
                          {i.attrValueName ? i.attrValueName : i.attrValue}
                        </Tag>
                      ))}
                    </span>
                  </div>
                </div>

                <div hidden={rulePattern === 'simplify'}>
                  <Select
                    style={{ width: 100 }}
                    className="margin-bottom"
                    placeholder="请选择"
                    allowClear
                    value={tag[0].rightBrackets}
                    onChange={value => {
                      const data1 = cloneDeep(data);
                      data1.ruleCondList[index].map(item => {
                        item.rightBrackets = value;
                      });
                      setData(data1);
                    }}
                  >
                    <Option value=")">)</Option>
                  </Select>
                  {index + 1 < data.ruleCondList.length ? (
                    <Select
                      style={{ width: 100, marginLeft: '8px' }}
                      className="margin-bottom"
                      placeholder="请选择"
                      allowClear
                      defaultValue={tag[0].preLog}
                      onChange={value => {
                        const data1 = cloneDeep(data);
                        data1.ruleCondList[index].map(item => {
                          item.preLog = value;
                        });
                        setData(data1);
                      }}
                    >
                      <Option value="||">OR</Option>
                      <Option value="&&">AND</Option>
                    </Select>
                  ) : null}
                </div>
              </>
            ))
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </div>

        <Divider className="small" />

        <div className="ant-detail-title">
          <span className="padding-right">结果设置</span>
          <span className="pull-right">
            <Button
              type="primary"
              ghost
              onClick={() => {
                setConditVisiable(true);
                setConditStatus('rule');
              }}
            >
              <Icon type="plus" />
              添加结果设置
            </Button>
          </span>
        </div>
        <div className={styles.rule_form}>
          {data.ruleConstList && data.ruleConstList.length > 0 ? (
            data.ruleConstList.map(tag => (
              <>
                <div className={styles.rule_title}>
                  {' '}
                  {tag[0].attr.attrId ? tag[0].attr.attrName : tag[0].attr.attrCode}
                </div>
                <div className={classNames(styles.rule_tag)} style={{ marginLeft: 0 }}>
                  {tag.map(i => (
                    <Tag key={i.attrValue}> {i.attrValueName ? i.attrValueName : i.attrValue}</Tag>
                  ))}
                </div>
              </>
            ))
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </div>
      </Spin>

      {/* 条件设置添加模态窗 */}
      {conditVisiable ? (
        <ConditionSet
          visiable={conditVisiable}
          close={() => {
            setConditVisiable(false);
          }}
          status={conditStatus}
          data={data}
          callback={callBack}
          result={result}
        />
      ) : null}

      {conditViewVisiable ? (
        <ConditionView
          visiable={conditViewVisiable}
          close={() => {
            setConditViewVisiable(false);
          }}
          data={data.ruleCondList ? data.ruleCondList : []}
          result={result}
        />
      ) : null}
    </>
  );
}

export default connect(({ ruleConfig2 }) => ({
  id: ruleConfig2.id,
}))(Form.create()(Content));
